package recharge

import (
	"context"
	"errors"

	schema "gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/dao/schema/recharge"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/svc"
	"github.com/zeromicro/go-zero/core/logc"
	"gorm.io/gorm"
)

const (
	_ = iota
	Active
	Inactive
)

const ()

type RechargeTypeModel struct {
	ctx context.Context
	db  *gorm.DB
}

func NewRechargeTypeModel(ctx context.Context, db *gorm.DB) *RechargeTypeModel {
	return &RechargeTypeModel{
		ctx: ctx,
		db:  db,
	}
}

func (model *RechargeTypeModel) getDb() *gorm.DB {
	if model.db != nil {
		return model.db
	}

	return svc.Db
}

func (model *RechargeTypeModel) GetAllRechargeTypes() ([]schema.RechargeType, error) {
	var rechargeTypes []schema.RechargeType
	res := model.getDb().Model(&schema.RechargeType{}).Where("status = ?", Active).Order("sort asc").Find(&rechargeTypes)
	if err := res.Error; err != nil {
		logc.Error(model.ctx, "RechargeTypeModel-getAllRechargeTypes,err", err)
		return nil, err
	}
	return rechargeTypes, nil
}

func (model *RechargeTypeModel) AdminAllRechargeTypes(name string) []schema.RechargeType {
	var rechargeTypes []schema.RechargeType

	orm := model.getDb().Model(&schema.RechargeType{})
	if name != "" {
		orm = orm.Where("name = ?", name)
	}
	res := orm.
		Order("sort asc").
		Find(&rechargeTypes)

	if err := res.Error; err != nil {
		logc.Error(model.ctx, "RechargeTypeModel-AdminAllRechargeTypes,err", err)
		return rechargeTypes
	}

	return rechargeTypes
}

func (model *RechargeTypeModel) GetRechargeTypesByName(name string) ([]schema.RechargeType, error) {
	var rechargeTypes []schema.RechargeType
	res := model.getDb().Model(&schema.RechargeType{}).Where("name = ? and status = ?", name, Active).Order("sort asc").Find(&rechargeTypes)
	if err := res.Error; err != nil {
		logc.Error(model.ctx, "RechargeTypeModel-getRechargeTypesByName,err", err)
		return nil, err
	}
	return rechargeTypes, nil
}

// UpdateRechargeType 更新充值类型
func (model *RechargeTypeModel) UpdateRechargeType(id int64, updateData map[string]interface{}) error {
	res := model.getDb().Model(&schema.RechargeType{}).Where("id = ?", id).Updates(updateData)
	if err := res.Error; err != nil {
		logc.Error(model.ctx, "RechargeTypeModel-updateRechargeType,err", err)
		return err
	}
	return nil
}

func (model *RechargeTypeModel) GetById(id int64) schema.RechargeType {
	var res schema.RechargeType
	dbRes := model.getDb().
		Model(&schema.RechargeType{}).
		Where("id = ?", id).First(&res)
	if err := dbRes.Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		logc.Error(model.ctx, "GetById,err", err)
	}

	return res
}
